import moment from 'moment';
import {Bookmark, getBookmarkPath} from "@/utils/bookmarkUtils";
import {Message, UrlOpenType} from "@/utils/constants";
import {getUrlOpenTypeValue} from "@/utils/utils";

/**
 * 转成书签对象
 * @param chromeBookmarks
 * @param folder
 * @param parent
 */
function traverse(chromeBookmarks: any[], folder: Bookmark[], parent: Bookmark | null) {
    chromeBookmarks.forEach(function (chromeBookmark) {
        // console.log("bookmark", bookmark);
        // console.log("bookmark.icon", bookmark.icon);
        let bookmark = new Bookmark("", "", [], "", "", parent);
        if (chromeBookmark.dateAdded) {
            let datetime = moment(chromeBookmark.dateAdded);
            bookmark.datetime = datetime.format('YYYY-MM-DD HH:mm:ss');
        }
        bookmark.path = getBookmarkPath(
            (chromeBookmark.title ? chromeBookmark.title : ""), parent, chromeBookmark.url === ""
        );
        // console.log("bookmark.path", bookmark.path);
        if (chromeBookmark.title) {
            bookmark.title = chromeBookmark.title;
        }
        // console.log("chromeBookmark.url", chromeBookmark.url)
        if (chromeBookmark.url) {
            bookmark.url = chromeBookmark.url;
        } else if (chromeBookmark.children) {
            let childFolder: any[] = [];
            traverse(chromeBookmark.children, childFolder, bookmark);
            if (childFolder) {
                bookmark.children = childFolder;
            }
        }
        if (bookmark.url || bookmark.children) {
            folder.push(bookmark);
        }
    });
    // console.log("folder：", folder);
}


/**
 * 获取浏览器的书签树
 */
function getChromeBookmarkTree() {
    return new Promise((resolve, reject) => {
        chrome.bookmarks.getTree(function (bookmarkTree: any[]) {
            let folder: any[] = [];
            console.log("bookmarkTree:", bookmarkTree);
            traverse(bookmarkTree, folder, null);
            console.log("folder", folder);
            if (folder.length > 0 && folder[0].children.length > 0) {
                resolve(folder[0].children[0].children);
            } else {
                resolve([]);
            }
        });
    });
}


/**
 * 打开插件网址
 */
function openChromeExtensionUrl() {
    let url = chrome.runtime.getURL('index.html');
    chromeOpenUrl(url);
}


/**
 * 存储数据到插件数据存储位置
 * @param key
 * @param obj
 */
function chromeStoreObjectToStorage(key: string, obj: Object) {
    // console.log("key", key);
    // console.log("obj", obj);
    chrome.storage.local.set({[key]: obj}, function () {
        if (chrome.runtime.lastError) {
            console.error('存储失败：', chrome.runtime.lastError);
        } else {
            console.log('对象存储成功。');
        }
    });
}


/**
 * 从插件数据存储位置中恢复数据
 * @param key
 */
async function chromeRestoreStorageToObject(key: string) {
    return new Promise((resolve) => {
        // 假设你使用 chrome.storage.local
        chrome.storage.local.get(key, function (result) {
            // console.log("result", result);
            resolve(result[key] || null);
        });
    });
}


/**
 * 打开网址
 * @param url
 * @param urlOpenType
 */
function chromeOpenUrl(url: string, urlOpenType: UrlOpenType | string = UrlOpenType.newTab) {
    console.log("url", url);
    console.log("urlOpenType", urlOpenType);
    let urlOpenTypeValue = getUrlOpenTypeValue(urlOpenType);
    urlOpenTypeValue = urlOpenTypeValue ? urlOpenTypeValue : urlOpenType;
    if (urlOpenTypeValue === UrlOpenType.newTab) {
        chrome.tabs.create({
            url: url
        }).then(tab => {

        });
    } else if (urlOpenTypeValue === UrlOpenType.currentTab) {
        chrome.tabs.query({active: true, currentWindow: true}, function (tabs: chrome.tabs.Tab[]) {
            if (tabs.length > 0) {
                let tab: chrome.tabs.Tab = tabs[0];
                if (!tab.id) {
                    console.log("当前没有打开的标签。")
                    return
                }
                chrome.tabs.update(tab.id, {url: url}).then(tab => {

                });
            }
        });
    } else if (urlOpenTypeValue === UrlOpenType.hideWindow) {
        chrome.windows.create({
            url: url,
            incognito: true
        }).then(tab => {

        });
    } else if (urlOpenTypeValue === UrlOpenType.newWindow) {
        chrome.windows.create({
            url: "https://www.example.com",
            type: "normal"
        }).then(tab => {

        });
    } else {
        console.error("未实现该链接打开方式：", urlOpenTypeValue);
    }
}


/**
 * 下载
 * @param url
 * @param filename
 * @param saveAs
 */
function chromeDownload(url: string, filename: string, saveAs: boolean = false) {
    chrome.downloads.download({
        url: url,
        filename: 'config_export.json',
        saveAs: true
    }).then();
}


/**
 * 发送消息
 * @param msg
 */
function chromeSendMessage(msg: Message) {
    console.log("msg", msg);
    chrome.runtime.sendMessage({"msg": msg}, response => {
        console.log(response);
    })
}


/**
 * SSO鉴权登录
 * @param createLoginURL
 * @param redirectRoute
 * @param parseResponse
 * @param refreshToken
 */
function chromeSSOAuthLogin(createLoginURL: Function, redirectRoute: string, parseResponse: Function, refreshToken?: string): Promise<string | null> {
    return new Promise((resolve, reject) => {
        let redirectUri = chrome.identity.getRedirectURL() + redirectRoute;
        let url = createLoginURL(redirectUri, refreshToken);
        chrome.identity.launchWebAuthFlow({
            url: url,
            interactive: !refreshToken,
            abortOnLoadForNonInteractive: false,
            timeoutMsForNonInteractive: 5000,
        } as any, async function (response) {
            if (chrome.runtime.lastError) {
                console.error("单点登录认证失败: ", chrome.runtime.lastError);
                reject(chrome.runtime.lastError);
                return
            }
            console.log("单点登录认证成功，结果: ", response);
            if (!response) {
                resolve(null);
                return
            }
            const accessToken = parseResponse(response);
            // console.log("accessToken", accessToken);
            resolve(accessToken);
        });
    });
}


/**
 * 查找书签路径
 * @param id
 * @param bookmarkPathStack
 */
async function chromeFindBookmarkPath(id: string, bookmarkPathStack: string[]): Promise<boolean> {
    const roots = await chrome.bookmarks.getTree();
    return findBookmarkPathRecursive(roots[0], id, bookmarkPathStack);
}


/**
 * 递归查找书签路径
 * @param bookmarkNode
 * @param targetId
 * @param bookmarkPathStack
 */
function findBookmarkPathRecursive(bookmarkNode: chrome.bookmarks.BookmarkTreeNode, targetId: string, bookmarkPathStack: string[]): boolean {
    if (bookmarkNode.id === targetId) {
        bookmarkPathStack.push(bookmarkNode.title);
        return true;
    }
    if (bookmarkNode.children) {
        for (const child of bookmarkNode.children) {
            if (findBookmarkPathRecursive(child, targetId, bookmarkPathStack)) {
                bookmarkPathStack.push(bookmarkNode.title);
                return true;
            }
        }
    }
    return false;
}


export {
    getChromeBookmarkTree,
    openChromeExtensionUrl,
    chromeStoreObjectToStorage,
    chromeRestoreStorageToObject,
    chromeOpenUrl,
    chromeDownload,
    chromeSendMessage,
    chromeSSOAuthLogin,
    chromeFindBookmarkPath,
};
